package swb.api.com.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import swb.api.com.repository.SysMenuRepository;
import swb.api.com.repository.dto.SysMenu;
import swb.api.com.service.SysMenuService;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class SysMenuServiceImpl implements SysMenuService {

    @Autowired
    private SysMenuRepository sysMenuRepository;

    @Override
    public List<SysMenu> getMenuTree() {
        List<SysMenu> allMenus = sysMenuRepository.findAll();
        return buildMenuTree(allMenus, 0L);
    }

    private List<SysMenu> buildMenuTree(List<SysMenu> allMenus, Long parentId) {
        List<SysMenu> tree = new ArrayList<>();
        for (SysMenu menu : allMenus) {
            if (parentId.equals(menu.getParentId())) {
                List<SysMenu> children = buildMenuTree(allMenus, menu.getId());
                menu.setChildren(children); // 此处将能正确调用
                tree.add(menu);
            }
        }
        return tree;
    }

    @Override
    public void save(SysMenu menu) {
        menu.setCreateTime(LocalDateTime.now());
        menu.setUpdateTime(LocalDateTime.now());
        sysMenuRepository.save(menu);
    }

    @Override
    public void update(SysMenu menu) {
        menu.setUpdateTime(LocalDateTime.now());
        sysMenuRepository.save(menu);
    }

    @Override
    public void delete(Long id) {
        sysMenuRepository.deleteById(id);
    }
}
